package top.hmtools.wxmp.server.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	private ObjectMapper objectMapper;

	/**
	 * 获取线程安全的当前请求的HttpServletRequest对象实例
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * 获取线程安全HttpServletResponse对象实例
	 * 
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}
	
	/**
	 * 格式化打印json字符串到控制台
	 * @param title
	 * @param obj
	 */
	protected synchronized void printFormatedJson(String title,Object obj) {
		if(this.objectMapper == null){
			this.objectMapper = new ObjectMapper();
		}
		try {
			//阿里的fastjson具有很好的兼容性，所以才多次一举
			String jsonString = JSON.toJSONString(obj);
			Object tempObj = JSON.parse(jsonString);
			String formatedJsonStr = this.objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(tempObj);
			this.logger.info("\n{}：\n{}",title,formatedJsonStr);
		} catch (JsonProcessingException e) {
			this.logger.error("格式化打印json异常：",e);
		}
	}
	
	
}
